/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PrincipalGUI.java
 *
 * Created on 21/04/2011, 22:37:31
 */
package br.com.fritadorcorrente.telas;

import br.com.fritadorcorrente.Fritador;
import br.com.fritadorcorrente.objetos.Comentario;
import br.com.fritadorcorrente.objetos.Email;
import br.com.fritadorcorrente.objetos.dao.EmailDAO;
import br.com.fritadorcorrente.objetos.dao.GenericoDAO;
import br.com.fritadorcorrente.utils.CamadaBase;
import br.com.fritadorcorrente.utils.TextComponentStream;
import br.com.fritadorcorrente.utils.spring.Contexto;
import com.meterware.httpunit.WebLink;
import java.awt.Color;
import java.io.PrintStream;
import java.util.HashMap;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;

/**
 *
 * @author manchini
 */
public class PrincipalGUI extends javax.swing.JFrame {

    private boolean ativo;

    /** Creates new form PrincipalGUI */
    public PrincipalGUI() {
        initComponents();
        //Mais tarde...
        System.setOut(new PrintStream(new TextComponentStream(jTextPane1, null)));
        System.setErr(new PrintStream(new TextComponentStream(jTextPane1, getErrorStyle())));

        jTable1.getColumnModel().removeColumn(jTable1.getColumn("Objeto"));

        CamadaBase.start();
        Contexto.getContext();

    }

    public Style getErrorStyle() {
        Style style = jTextPane1.getStyledDocument().addStyle("error",
                null);
        StyleConstants.setForeground(style, Color.red);

        return style;
    }

    private void fritar() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                fritarRun();
            }
        }).start();
    }

    private void fritarRun() {
        ativo = true;
        jButton1.setText("Fritando");
        HashMap<String, WebLink> links = new HashMap<String, WebLink>();
        try {
            String emailBase = jTextField_email.getText();
            String urlBase = jTextField_site_ini.getText();

            Email email = (Email) Contexto.getContext().getBean(GenericoDAO.class).carregar(Email.class, emailBase);
            if (email == null) {
                email = Contexto.getContext().getBean(Email.class);
                email.setEmail(emailBase);
                email = (Email) Contexto.getContext().getBean(GenericoDAO.class).gravar(email);
            }
            atualizarTabela(email);

            while (ativo) {

                if (!Contexto.getContext().getBean(EmailDAO.class).getEmailSiteJaUsado(email, urlBase)) {
                    Fritador.TestarFormulario(urlBase, email);
                    Contexto.getContext().getBean(GenericoDAO.class).gravar(email);
                    atualizarTabela(email);
                }
                WebLink[] listaLinks = Fritador.listaLinks(urlBase);
                for (int i = 0; i < listaLinks.length; i++) {
                    WebLink webLink = listaLinks[i];
                    links.put(Fritador.getDominio(webLink.getURLString()), webLink);
                }

                urlBase = links.get(links.keySet().toArray()[new Double(Math.random() * links.keySet().size()).intValue()]).getURLString();

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }finally{
            jButton1.setText("Fritar");
        }

    }

    private void atualizarTabela(Email email) {
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        model.setNumRows(0);
        if (email.getMensagens() == null) {
            return;
        }

        for (int i = 0; i < email.getMensagens().size(); i++) {
            Comentario object = (Comentario) email.getMensagens().toArray()[i];
            Object[] row = new Object[3];
            row[0] = object.getDominio();
            row[1] = object.getMensagem().getMensagem();
            row[2] = object;
            model.addRow(row);

        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField_email = new javax.swing.JTextField();
        jPanel5 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextField_site_ini = new javax.swing.JTextField();
        jPanel6 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.LINE_AXIS));

        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.Y_AXIS));

        jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel1.setText("E-mail");
        jLabel1.setOpaque(true);
        jLabel1.setPreferredSize(new java.awt.Dimension(80, 18));
        jPanel4.add(jLabel1);

        jTextField_email.setPreferredSize(new java.awt.Dimension(250, 30));
        jTextField_email.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField_emailActionPerformed(evt);
            }
        });
        jPanel4.add(jTextField_email);

        jPanel1.add(jPanel4);

        jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel2.setText("Site Inicial:");
        jLabel2.setOpaque(true);
        jLabel2.setPreferredSize(new java.awt.Dimension(80, 18));
        jPanel5.add(jLabel2);

        jTextField_site_ini.setPreferredSize(new java.awt.Dimension(250, 30));
        jTextField_site_ini.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField_site_iniActionPerformed(evt);
            }
        });
        jPanel5.add(jTextField_site_ini);

        jPanel1.add(jPanel5);

        jButton1.setText("Fritar");
        jButton1.setOpaque(true);
        jButton1.setPreferredSize(new java.awt.Dimension(80, 34));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel6.add(jButton1);

        jButton2.setText("Cadastrar Mensagem");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel6.add(jButton2);

        jPanel1.add(jPanel6);

        jPanel3.add(jPanel1, java.awt.BorderLayout.NORTH);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null}
            },
            new String [] {
                "Site", "Mensagem", "Objeto"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel3);

        jPanel7.setPreferredSize(new java.awt.Dimension(400, 444));
        jPanel7.setLayout(new java.awt.BorderLayout());

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder("Log"));
        jScrollPane2.setViewportView(jTextPane1);

        jPanel7.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel7);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-864)/2, (screenSize.height-533)/2, 864, 533);
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField_emailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_emailActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_jTextField_emailActionPerformed

    private void jTextField_site_iniActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_site_iniActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField_site_iniActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (ativo == false) {
            fritar();
        } else {
            ativo = false;
            jButton1.setText("Fritar");
        }
}//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        new MensagemGUI(this, false).setVisible(true);
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PrincipalGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField_email;
    private javax.swing.JTextField jTextField_site_ini;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables
}
